<script setup lang="ts">
import { HttpHelper } from "../lib/HttpHelper";
import { Menu as iconmenu } from '@element-plus/icons-vue'
import { ref, onMounted, shallowRef } from 'vue';
import { useRouter } from 'vue-router';

import { Global } from '../Global';
import { AuthService } from '@/apis/admin/auth';
import MyKeepAlive from "@/lib/MyKeepAlive";
import { SystemEvent } from "@/lib/SystemEvent";

const router = useRouter();
const editableTabs = ref(<any[]>[]);
const selectedTab = ref("");

const modifyPwdFormVisible = ref(false);
const modifyPwdData = ref({ oldPwd: "", newPwd: "" });
const isBusy = ref(false);

const includeComponents = ref(<any[]><any>[]);
const menus = ref(<any[]>[]);
const showMenu = ref(true);
const allmenus = <any[]>[];
const setupCode = ref();
const dialogGoogleCodeVisible = ref(false);
const childView = shallowRef(<any>null);
const title = ref();
const pushToAllMenus = (datas: any[]) => {
  datas?.forEach(x => {
    x.Id = x.Id + '';
    allmenus.push(x);
    pushToAllMenus(x.Items);
  });
}

onMounted(() => {
  title.value = document.title.split(' ')[0];
  bindMenus();

  SystemEvent.registerEvent("goView" , (path:any)=>{
    var menu = allmenus.find((x:any)=>x.Path == path);
    if(menu){
      menuClick(menu.Id,<any>null);
    }
  });
});

/**绑定菜单 */
const bindMenus = async () => {
  try {
    var obj = await HttpHelper.get(`/Auth/GetLogoTitle`, null);
    if (obj) {
      console.log(obj);
      Global.Title = JSON.parse(obj);
    }
    title.value = Global.Title.SystemShort;

    obj = await HttpHelper.get(`/Auth/MustGoogleAuthenticator`, { issuer: Global.Title.System });
    if (obj) {
      setupCode.value = JSON.parse(obj);
      dialogGoogleCodeVisible.value = true;
    }

    var items = await AuthService.GetMenus();
    pushToAllMenus(items);
    menus.value = items;

    allmenus.push({
      Id: "-1",
      Path: "home/IndexView",
      Caption: "首页"
    });
    menuClick("-1", <any>null);
  } catch (err) {
    Global.showError(err);
  }
}

const menuClick = (index: any, indexPath: any[]) => {
  console.log("菜单点击", index, indexPath);

  var item = allmenus.find(x => x.Id == index);
  if (item) {
    if (item.Path) {
      console.log("菜单路径：", item.Path);
      if (editableTabs.value.findIndex(x => x.Id == item.Id) >= 0) {

      }
      else {
        editableTabs.value.push(item);
      }

      selectedTab.value = item.Id;
      var view = Global.asyncLoadView(item.Path);
      includeComponents.value.push(view);
      childView.value = view;
    }
  }
}

const tabChange = (menuid: string) => {
  console.log("tabChange", menuid);

  selectedTab.value = menuid;
  var tabData = editableTabs.value.find(x => x.Id == menuid);
  childView.value = Global.asyncLoadView(tabData.Path);
}

const closeAllTabClick = () => {
  editableTabs.value = [];
  includeComponents.value = [];
  Global.removeAllViewCache();
  selectedTab.value = "";
  childView.value = null;
  menuClick("-1", <any>null);
}

const tabClose = (menuid: string) => {
  console.log("关闭", menuid);
  if (menuid == "-1")
    return;

  var tabindex = editableTabs.value.findIndex(x => x.Id == menuid);
  if (tabindex >= 0) {
    editableTabs.value.splice(tabindex, 1);
  }

  var menuitem = allmenus.find(x => x.Id == menuid);
  if (menuitem) {
    console.log("被关闭的是", menuitem.Caption);
    var view = Global.removeViewCache(menuitem.Path);
    var index = includeComponents.value.indexOf(view);
    if (index >= 0) {
      includeComponents.value.splice(index, 1);
    }
  }

  if (selectedTab.value == menuid) {
    if (editableTabs.value.length) {
      var tabData = editableTabs.value[editableTabs.value.length - 1];
      selectedTab.value = tabData.Id;
      childView.value = Global.asyncLoadView(tabData.Path);
    }
    else {
      selectedTab.value = "";
      childView.value = null;
    }
  }
}

const exitLogin = () => {
  Global.UserInfo.Token = "";
  router.replace("/login");
}

const toggleMenu = () => {
  showMenu.value = !showMenu.value;
}

const submitModifyPwdClick = async () => {
  try {
    isBusy.value = true;
    await HttpHelper.postForm(`/Auth/ModifyPassword`, modifyPwdData.value);
    Global.showInfo("成功修改密码");
    modifyPwdFormVisible.value = false;
  } catch (error) {
    Global.showError(error);
  }
  finally {
    isBusy.value = false;

  }
}

const bindedGoogleClick = async () => {
  if (window.confirm("您确定已经绑定好谷歌验证码吗？\r\n如果没有绑定好，下次您将无法登录本系统！")) {
    try {
      isBusy.value = true;
      await HttpHelper.get(`/Auth/BindGoogleAuthenticator`, null);

      dialogGoogleCodeVisible.value = false;
    } catch (error) {
      Global.showError(error);
    }
    finally {
      isBusy.value = false;

    }
  }
}
</script>

<template>
  <el-container>
    <!-- 谷歌验证码 -->
    <el-dialog v-model="dialogGoogleCodeVisible" :close-on-click-modal="false" :show-close="false">
      <div style="text-align: center;">
        <img :src="setupCode.QrCodeSetupImageUrl" />
      </div>
      <div style="margin: 20px 0;text-align: center;line-height: 30px;">手动绑定<br>{{ setupCode.ManualEntryKey }}</div>
      <template #footer>
        <div class="dialog-footer" style="text-align: center;">
          <el-button @click="exitLogin">退出系统</el-button>
          <el-button type="primary" :loading="isBusy" @click="bindedGoogleClick">
            我已完成谷歌App的绑定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 左边菜单 -->
    <el-aside class="leftarea" v-show="showMenu">
      <!-- 头像 -->
      <div class="avatar" style="display: flex;flex-direction: row;">
        <div style="position: relative;">
          <img src="../assets/cover.jpg">
          <div
            style="position: absolute;right: 0;bottom:0;background-color: #0aa699;width: 12px;height: 12px;border-radius: 12px;">
          </div>
        </div>
        <div style="flex:1;padding-left: 18px;">
          <div style="font-size: 19px;color: #ffffff;font-weight: 600;">{{ title }}</div>
          <div
            style="width:70%;font-size: 13px;color: #929fa5;white-space: nowrap;overflow: hidden;text-overflow: ellipsis;">
            {{ Global.UserInfo.Role }}</div>
        </div>
      </div>

      <div style="padding-left: 20px;padding-bottom: 20px;">
        <div style="color: #535862;font-size: 11px;font-weight: 600;letter-spacing: 0.9px;">
          BROWSE
        </div>
      </div>

      <el-scrollbar style="flex:1;min-height: 0px;">
        <!-- 菜单 -->
        <el-menu active-text-color="#ffd04b" :unique-opened="true" background-color="#1b1e24" text-color="#8b91a0"
          :default-active="selectedTab" @select="menuClick">
          <!-- 1级菜单 -->
          <template v-for="menu in menus">
            <el-sub-menu :index="menu.Id" v-if="menu.Items.length">
              <template #title>
                <el-icon v-if="menu.Icon">
                  <component :is="menu.Icon" />
                </el-icon>
                <span>{{ menu.Caption }}</span>
              </template>

               <!-- 2级菜单 -->
              <template v-for="submenu1 in menu.Items">
                <el-sub-menu :index="submenu1.Id" v-if="submenu1.Items.length">
                  <template #title>
                    <span>{{ submenu1.Caption }}</span>
                  </template>

                   <!-- 3级菜单 -->
                  <template v-for="submenu2 in submenu1.Items">
                    <el-menu-item :index="submenu2.Id">
                      <span>{{ submenu2.Caption }}</span>
                    </el-menu-item>
                  </template>
                </el-sub-menu>
                <el-menu-item :index="submenu1.Id" v-else>
                  <span>{{ submenu1.Caption }}</span>
                </el-menu-item>
              </template>

            </el-sub-menu>
            <el-menu-item :index="menu.Id" v-else>
              <span>{{ menu.Caption }}</span>
            </el-menu-item>
          </template>
        </el-menu>

      </el-scrollbar>

    </el-aside>

    <!-- 内容 -->
    <el-main class="container">
      <el-container>
        <el-header class="toparea">
          <div class="top-tools-item bright" @click="toggleMenu">
            <el-icon>
              <iconmenu />
            </el-icon>
          </div>

          <el-tabs closable class="top-tabs" v-model="selectedTab" @tab-change="tabChange" @tab-remove="tabClose">
            <el-tab-pane v-for="item in editableTabs" :key="item.Id" :label="item.Caption" :name="item.Id">
              <template #label>
                <el-dropdown trigger="contextmenu">
                  <span class="tabcap">{{ item.Caption }}</span>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="closeAllTabClick">关闭所有页面</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-tab-pane>
          </el-tabs>
          <div class="iconarea">
            <img src="../assets/cover.jpg">
            <el-dropdown trigger="click">
              <div style="cursor: pointer;display: flex;align-items: center;margin-left: 10px;">
                <div style="flex: 1;font-size: 13px;font-weight: 600;">{{ Global.UserInfo.Name }}</div>
                <span class="caret" style="margin-left: 5px;"></span>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="modifyPwdFormVisible = true">修改密码</el-dropdown-item>
                  <el-dropdown-item @click="exitLogin">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        <el-main>
          <MyKeepAlive :include="includeComponents">
            <component :is="childView" />
          </MyKeepAlive>
        </el-main>
      </el-container>

    </el-main>
  </el-container>

  <el-dialog v-model="modifyPwdFormVisible" title="修改密码" :close-on-click-modal="false" width="500">
    <el-form ref="formRef" :model="modifyPwdData" label-width="auto"
      @keypress.native.enter.prevent="submitModifyPwdClick">
      <el-form-item label="旧密码" prop="oldPwd">
        <el-input type="password" show-password v-model="modifyPwdData.oldPwd" />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input type="password" show-password v-model="modifyPwdData.newPwd" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="modifyPwdFormVisible = false">取消</el-button>
        <el-button type="primary" :loading="isBusy" @click="submitModifyPwdClick">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
/*改变tabs高度 */
:deep(.el-tabs.top-tabs) {
  --el-tabs-header-height: 25px !important;
}

.top-tabs {
width: 10px;
  /*去掉长下划线 */
  :deep(.el-tabs__nav-wrap:after) {
    height: 0 !important;
  }

  :deep(.el-tabs__header) {
    margin: 0 !important;
  }

  /*去掉选中后蓝色下划线 */
  :deep(.el-tabs__active-bar) {
    background-color: transparent !important;
  }

  :deep(.el-tabs__nav-next){
    margin-top: -8px;
  }
  :deep(.el-tabs__nav-prev){
    margin-top: -8px;
  }


  :deep(.el-tabs__item) {
    border: 1px solid #909399;
    color: #909399;
    border-radius: 100px;
    padding: 0 !important;
    padding-left: 15px !important;
    padding-right: 15px !important;
    margin-left: 10px !important;

    .tabcap {
      color: #909399;
    }

    .el-icon {
      display: none !important;
    }
  }

  :deep(.el-tabs__item:hover) {

    .el-icon {
      display: inline !important;
    }
  }

  :deep(.el-tabs__item.is-active) {
    background-color: #909399;
    color: #fff;
    border: 0;

    .tabcap {
      color: #fff;
    }

  }
}

.container {
  background-color: var(--main-bg-color);

  .toparea {
    background-color: #fff;
    height: 60px;
    box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.2);
    display: flex;
    flex-direction: row;
    align-items: center;
    z-index: 1;

    .top-tabs {
      flex: 1;


    }

    .bright {
      border-right: 1px solid rgba(0, 0, 0, 0.14);
    }

    .bleft {
      border-left: 1px solid rgba(0, 0, 0, 0.14);
    }

    .top-tools-item {
      height: 100%;
      color: #7a7f8c;
      cursor: pointer;
      display: flex;
      justify-content: center;
      align-items: center;
      width: 62px;

      font-size: 22px;
    }

    .top-tools-item:hover {
      background-color: #eee;
    }

    .iconarea {
      display: flex;
      flex-direction: row;
      align-items: center;
      margin-left: 20px;
      margin-right: 20px;

      img {
        width: 32px;
        height: 32px;
        border-radius: 32px;
      }
    }
  }

  .el-main {
    padding: 0px;
    overflow: hidden;


  }
}



.el-main {
  padding: 0;
}

.el-header {
  padding: 0;
  --el-header-height: auto;
}



.el-avatar {
  --el-avatar-bg-color: #38a0f4;
}

.avatar {
  padding: 20px;

  img {
    width: 46px;
    height: 46px;
    border-radius: 46px;
  }

  .name {
    padding-top: 15px;
    font-weight: 600;
    font-size: 13px;

    .label {
      text-overflow: ellipsis;
      overflow: hidden;
      white-space: nowrap;

      span {
        font-weight: normal;
      }
    }
  }

  .el-dropdown-link {
    color: #fff;
    display: flex;
    flex-direction: row;
    width: 100%;
  }
}

.el-dropdown-link {
  cursor: pointer;
}

.leftarea {
  font-family: 'Roboto';
  background-color: #1b1e24;
  width: 250px;
  background-repeat: no-repeat;
  background-size: 80%;
  background-position: top right;
  display: flex;
  flex-direction: column;

  :deep(li.el-sub-menu[aria-expanded="true"] > div:first-child) {
    color: #ffffff;
  }

  :deep(li.el-sub-menu[aria-expanded='true']) {

    .el-menu {
      background-color: #22262e;
    }

    .el-menu-item {
      height: 40px !important;
    }
  }


  .el-menu-item.is-active {
    color: #ffd04b;
  }

  .el-menu {
    --el-menu-item-height: 40px;
  }

  .el-menu {
    font-weight: 600;
    border-right: 0;
  }


}
</style>